//
//  HomeViewController.m
//  SheShiDu
//
//  Created by 单剑秋 on 16/6/11.
//  Copyright © 2016年 单剑秋. All rights reserved.
//

#import "HomeViewController.h"
#import "CycleTableViewCell.h"
#import "SDCycleScrollView.h"
#import "ButtonTableViewCell.h"
#import "PackageTableViewCell.h"
#import "VerticalTableViewCell.h"
#import "BanderViewController.h"
#import "AdvantageViewController.h"
#import "LocationViewController.h"
#import "LocationButton.h"
#import "PersonalViewController.h"
#import <CoreLocation/CoreLocation.h>

#import "LoadingViewController.h"
#import "RegisterViewController.h"

@interface HomeViewController ()<UITableViewDelegate, UITableViewDataSource, SDCycleScrollViewDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) UITableView *wholeTableView;
@property (nonatomic, strong) NSMutableArray *picArr;
@property (nonatomic, strong) LocationButton *locationBtn;
@property (nonatomic, strong) NSString *cityStr;
 
@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.picArr = [NSMutableArray array];
  
    for (int i = 0; i < 4; i++) {
        NSString *picStr = [NSString stringWithFormat:@"tu%d",i];
        UIImage *totol = [UIImage imageNamed:picStr];
        [_picArr addObject:totol];
//        NSLog(@"%@", picStr);
    }
    
    [self addTableView];
    [self location];
    
}

- (void)location
{
    //定位按钮设置
    self.locationBtn = [LocationButton buttonWithType:UIButtonTypeCustom];
    _locationBtn.frame = CGRectMake( 0, 20, 80, 22);
    [_locationBtn setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
    [self.locationBtn setTitle:_cityStr forState:UIControlStateNormal];
    [_locationBtn addTarget:self action:@selector(locationBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_locationBtn aboveSubview:_wholeTableView];

        // 定位管理器
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc] init];
        // 设置代理
        _locationManager.delegate = self;
        // 设置定位精确度到米
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 设置过滤器为无
        _locationManager.distanceFilter = kCLDistanceFilterNone;
        [_locationManager requestWhenInUseAuthorization];
        // 开始定位
        [_locationManager startUpdatingLocation];
    }
    
    

}

- (void)addTableView
{
    
    self.wholeTableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _wholeTableView.delegate = self;
    _wholeTableView.dataSource = self;
    _wholeTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _wholeTableView.allowsSelection = NO;
    [self.view addSubview:_wholeTableView];
    
    self.wholeTableView.bounces = NO;
    
    [_wholeTableView registerClass:[CycleTableViewCell class] forCellReuseIdentifier:@"CycleCell"];
    [_wholeTableView registerClass:[ButtonTableViewCell class] forCellReuseIdentifier:@"ButtonCell"];
    [_wholeTableView registerClass:[VerticalTableViewCell class] forCellReuseIdentifier:@"Vertical"];
    [_wholeTableView registerClass:[PackageTableViewCell class] forCellReuseIdentifier:@"test"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
        return 1;
    } else if (section == 3) {
        return 0;
    } else {
        return 2;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            CycleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CycleCell" forIndexPath:indexPath];
            cell.cycleView.delegate = self;
            cell.cycleView.localizationImageNamesGroup = _picArr;

            return cell;
        } else {
            ButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ButtonCell" forIndexPath:indexPath];
            [cell.materialButton addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
    } else if (indexPath.section == 1) {
        VerticalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Vertical" forIndexPath:indexPath];
        if (indexPath.row == 0) {
            [cell.mainButton setImage:[UIImage imageNamed:@"new"] forState:UIControlStateNormal];
        } else {
            [cell.mainButton setImage:[UIImage imageNamed:@"old"] forState:UIControlStateNormal];
        }
        return cell;
    } else {
        PackageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"test"];
        return cell;
    }
 
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 3)];
    backView.backgroundColor = [UIColor colorWithRed:237 / 255.0 green:231 / 255.0 blue:227 / 255.0 alpha:1];
    return backView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat Height = 0;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            Height = SCREEN_HEIGHT * (378 / 1334.0);
           
        } else if (indexPath.row == 1) {
            Height = SCREEN_HEIGHT * (202 / 1334.0);
        }
    } else if (indexPath.section == 1) {
        Height = SCREEN_HEIGHT * (210 / 1334.0);
    } else {
        Height = SCREEN_HEIGHT * (217 / 1334.0);
    }
    return Height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    } else {
        return 3;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// 点击方法
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    BanderViewController *banderVC = [[BanderViewController alloc]init];
    [banderVC.navigationController setNavigationBarHidden:YES animated:YES];
    [banderVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:banderVC animated:YES];
}

- (void)buttonAction {
//    AdvantageViewController *advantageVC = [[AdvantageViewController alloc]init];
//    [self.navigationController pushViewController:advantageVC animated:YES];
    LoadingViewController *loadVC = [[LoadingViewController alloc]init];
    [self.navigationController presentViewController:loadVC animated:YES completion:^{
        
    }];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *currentLocation = [locations lastObject];
    // 获取当前城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks firstObject];
            NSLog(@"%@", placemark.name);
            self.cityStr = [placemark.addressDictionary objectForKey:@"City"];
            if (!_cityStr) {
                _cityStr = placemark.administrativeArea;
            }
            _cityStr = [_cityStr stringByReplacingOccurrencesOfString:@"市" withString:@""];
            [self.locationBtn setTitle:_cityStr forState:UIControlStateNormal];
            
            PersonalViewController *perVC = [[PersonalViewController alloc]init];
            UINavigationController *personalNavi = [[UINavigationController alloc]initWithRootViewController:perVC];
            personalNavi.tabBarItem.image = [UIImage imageNamed:@"我的"];
            personalNavi.tabBarItem.selectedImage = [[UIImage imageNamed:@"个人中心s"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            personalNavi.tabBarItem.title = @"个人中心";
            perVC.location = _cityStr;
            NSMutableArray *newArr = [NSMutableArray arrayWithArray:self.tabBarController.viewControllers];
            [newArr replaceObjectAtIndex:3 withObject:personalNavi];
            self.tabBarController.viewControllers = newArr;
//            perVC.location = _cityStr;
//            WEAKSELF(weakSelf);
//            weakSelf.location = [NSMutableDictionary dictionaryWithObjectsAndKeys:_cityStr, @"name", nil];
//            weakSelf.reBackL(_location);
            NSLog(@"%@", _cityStr);
            
        } else if (error == nil && placemarks.count == 0) {
            NSLog(@"NO results");
        } else if (error != nil) {
            NSLog(@"%@cccccc",error);
        }
    }];
    [_locationManager stopUpdatingLocation];
}

- (void)locationBtnAction
{
    void (^cityStr)(NSString *str) = ^(NSString *str) {
        [_locationBtn setTitle:str forState:UIControlStateNormal];
        
    };
    LocationViewController *locationVC = [[LocationViewController alloc]init];
    locationVC.cityStr = cityStr;
    locationVC.locationStr = self.cityStr;
    [self.navigationController pushViewController:locationVC animated:YES];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if (error.code == kCLErrorDenied) {
        NSLog(@"hhe");
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
